//
//  WCNetWorkParamHandler.m
//  ZZNetWorker_Example
//
//  Created by ZengLiZhi on 2024/3/22.
//  Copyright © 2024 zenglizhi. All rights reserved.
//

#import "WCNetWorkParamHandler.h"
#import "NSObject+MJKeyValue.h"
#import "NSData+TLHash.h"
#import "NSData+TLBase64.h"
#import "NSString+TLURL.h"
#import "AntonyKeychainStore.h"


#define WCAPP_secret @"qRKOwI3iZ46vVarlZhljNy8H9WPwmK8n"
#define WCAPP_appId @"96aF6RWT"

#define CryptoAESKey @"A3PsjK10D-TawPW="

@implementation WCNetWorkParamHandler

- (id)handleParamWithRequest:(ZZNetWorkRequest *)request{
    
    
    if (request.willHandlerParam) {
        if (!request.param) {
            request.param = @{};
        }
        
        id param = request.param;
        
        NSDictionary *generateSignature = nil;
        if (request.method == FormData) {
            generateSignature = [self generateSignatureWithData:@{} url:request.signApi?request.signApi:request.api params:@{} method:request.method];
        }else{
            generateSignature = [self generateSignatureWithData:param url:request.signApi?request.signApi:request.api params:@{} method:request.method];
        }
        [self setHTTPHeaderFieldWithRequest:request param:generateSignature];
    }

    return request.param;
}

- (NSDictionary *)generateSignatureWithData:(id)data url:(NSString *)url params:(NSDictionary *)params method:(ZZNetWorkerMethod)workMethod {
    NSString *appTerminalType = @"ios";
    
    NSString *signUrl = url;
   
    NSMutableString *str = [[NSMutableString alloc] initWithString:signUrl];
    if (![str hasPrefix:@"/"]){
        [str insertString:@"/" atIndex:0];
    }
    
    NSString *paramString = [self.class sortByASCII:params];
    if (paramString.length > 0){
        [str appendString:@"?"];
        [str appendString:paramString];
    }
    
    if ([data isKindOfClass:[NSArray class]]) {
        NSString *arrayString = [data mj_JSONString];
        [str appendString:arrayString];
    } else if ([data isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *dataSortDic = [[NSMutableDictionary alloc] initWithDictionary:data];
        [dataSortDic removeObjectForKey:@"file"];
        if (dataSortDic.count > 0){
            NSString *jsonString = [dataSortDic mj_JSONString];
            [str appendString:jsonString];
        }else{
            if (workMethod == GET) {
                [str appendString:@""];
            } else {
                [str appendString:@"{}"];
            }
        }
    } else {
        
    }
    
    NSString *timestamp = [NSString stringWithFormat:@"%lld",(long long int)([NSDate date].timeIntervalSince1970*1000)];
    [str appendString:timestamp];
   
    NSString *nonce = [self getRandStringWithLength:10];
    [str appendString:nonce];

    NSData *data1 = [str dataUsingEncoding: NSUTF8StringEncoding];
    NSData *keyData = [[WCAPP_secret dataUsingEncoding: NSUTF8StringEncoding] mutableCopy];
    NSData *sign2 = [data1 hmacSHA1DataWithKey:keyData];
    
    NSString *base64 = [sign2 base64EncodedString];
    NSString *finalSign = [base64 urlEncode];
 
    NSDictionary *dic = @{
        @"signature" :finalSign,
        @"timestamp" :timestamp,
        @"nonce":nonce,
        @"appTerminalType" :appTerminalType,
        @"appId":WCAPP_appId
    };
    
//    ZZLog(@"str : %@ \n ",str);
//    ZZLog(@"sign2 : %@ \n base64 : %@ \n finalSign : %@ \n",sign2,base64,finalSign);
//    ZZLog(@"\ngenerateSignature : %@\n",dic);
    return dic;
}
/**
 https://dev-gw-oem.botsmart.net/api/auth/company/login
 str : /auth/company/login{"phone":"13500001001","smsCode":"666666","loginChannel":"APP"}1711353923616f6q3yh53hs
  
 ZZNetWorker+generateSignature.m:(82): sign2 : {length = 20, bytes = 0xf290b3a93176dafd167aa3bb38ab90bdf983029b}
  base64 : 8pCzqTF22v0WeqO7OKuQvfmDAps=
  finalSign : 8pCzqTF22v0WeqO7OKuQvfmDAps%3D
 
 [10]    (null)    @"User-Agent" : @"xinHuaMiaoBiProject/1.0.0 (iPhone; iOS 17.1; Scale/3.00)"
 
    zz:
 str : /auth/company/login{"phone":"13500001001","smsCode":"666666","loginChannel":"APP"}1711356286486ujmgr7104w
  
 WCNetWorkParamHandler.m:(101): sign2 : {length = 20, bytes = 0x7e0e61aa179c6c79af314af9d19956f28af1e075}
  base64 : fg5hqhecbHmvMUr50ZlW8orx4HU=
  finalSign : fg5hqhecbHmvMUr50ZlW8orx4HU%3D
 */

- (void)setHTTPHeaderFieldWithRequest:(ZZNetWorkRequest *)request param:(NSDictionary *)dic{
    
    NSString *versionStr = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    NSString *buildStr = [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey];
    
    [request.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request.manager.requestSerializer setValue:dic[@"appTerminalType"] forHTTPHeaderField:@"app-terminal-type"];
    [request.manager.requestSerializer setValue:buildStr forHTTPHeaderField:@"app-version-code"];
    [request.manager.requestSerializer setValue:versionStr forHTTPHeaderField:@"appVersion"];
    [request.manager.requestSerializer setValue:@"ismbgov001" forHTTPHeaderField:@"channel"];
    [request.manager.requestSerializer setValue:[AntonyKeychainStore getUUIDByKeyChain] forHTTPHeaderField:@"deviceId"];
    
    [request.manager.requestSerializer setValue:dic[@"appId"] forHTTPHeaderField:@"apiSign-appId"];
    [request.manager.requestSerializer setValue:dic[@"timestamp"] forHTTPHeaderField:@"apiSign-timestamp"];
    [request.manager.requestSerializer setValue:dic[@"nonce"] forHTTPHeaderField:@"apiSign-nonce"];
    [request.manager.requestSerializer setValue:dic[@"signature"] forHTTPHeaderField:@"apiSign-sign"];
    [request.manager.requestSerializer setValue:@"APP" forHTTPHeaderField:@"Login-Channel"];
    [request.manager.requestSerializer setValue:@"APP" forHTTPHeaderField:@"loginChannel"];
    [request.manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"Channel-Customization-Id"];
    
    if (request.authorization.length){
        [request.manager.requestSerializer setValue:request.authorization forHTTPHeaderField:@"Auth-Token"];
    }
    NSString *idfaStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"IDFAString"];
    if (idfaStr && idfaStr.length >= 14) {
    } else {
        idfaStr = @"";
    }
    [request.manager.requestSerializer setValue:idfaStr forHTTPHeaderField:@"idfa"];
    return;
}

+(NSString *)sortByASCII:(NSDictionary*)dict{
    if (dict == nil) {
        return @"";
    }
    NSArray*allKeyArray = [dict allKeys];
    NSArray*afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1,id _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for(NSString * sortsing in afterSortKeyArray) {
        NSString * valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    NSMutableString *signString = [NSMutableString string];
    for(int i =0; i < afterSortKeyArray.count; i++) {
        if (i==0) {
             NSString * keyValue = [NSString stringWithFormat:@"%@=%@",afterSortKeyArray[i],valueArray[i]];
            [signString appendString:keyValue];
        }else{
            NSString * keyValue = [NSString stringWithFormat:@"&%@=%@",afterSortKeyArray[i],valueArray[i]];
            [signString appendString:keyValue];
        }
    }
    return [signString copy];
}

//产生length个长度随机字符串
- (NSString *)getRandStringWithLength:(int)length {
    NSString *sourceStr = @"0123456789abcdefghijklmnopqrstuvwxyz";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    for (int i = 0; i < length; i++) {
        unsigned index = arc4random() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
@end
